package drds.plus.sql_process.abstract_syntax_tree.expression.bind_value;

import drds.plus.common.jdbc.Parameters;
import drds.plus.common.jdbc.SetParameterMethodAndArgs;
import drds.plus.sql_process.abstract_syntax_tree.IExecutePlanVisitor;
import drds.plus.sql_process.abstract_syntax_tree.expression.NullValue;
import drds.plus.sql_process.optimizer.OptimizerException;
import lombok.Getter;
import lombok.Setter;

/**
 * 绑定变量
 */
public class BindValueImpl implements BindValue {
    @Setter
    @Getter
    protected int index;
    @Setter
    @Getter
    protected Object value;

    public BindValueImpl(int index) {
        this.index = index;
    }

    public int compareTo(Object o) {
        throw new UnsupportedOperationException();
    }

    public Object assignment(Parameters parameters) {
        SetParameterMethodAndArgs setParameterMethodAndArgs = parameters.getIndexToSetParameterMethodAndArgsMap().get(index);
        if (setParameterMethodAndArgs == null) {
            throw new OptimizerException("can't find param by index :" + index + " ." + "context : " + parameters);
        }
        if (setParameterMethodAndArgs.getArgs()[1] == null) {
            value = NullValue.getNullValue();
        } else {
            value = setParameterMethodAndArgs.getArgs()[1];
        }
        if (parameters.isBatch()) {
            // 针对batch，不做绑定变量替换
            return this;
        } else {
            return value;
        }
    }

    public String toString() {
        return "BindValueImpl [index=" + index + ", value=" + value + "]";
    }


    public void accept(IExecutePlanVisitor executePlanVisitor) {
        executePlanVisitor.visit(this);
    }


    public BindValue copy() {
        BindValueImpl bindValue = new BindValueImpl(index);
        return bindValue;
    }

}
